﻿namespace Pub.Class
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Text;

    public class HttpHelper
    {
        private static System.Text.Encoding _encoding;
        private static System.Text.Encoding _postDataEncoding;

        private static CookieCollection ConvertCookieArraysToCookieCollection(ArrayList al, string strHost)
        {
            CookieCollection cookies = new CookieCollection();
            int count = al.Count;
            for (int i = 0; i < count; i++)
            {
                string[] strArray = al[i].ToString().Split(new char[] { ';' });
                int length = strArray.Length;
                string str2 = string.Empty;
                string str3 = string.Empty;
                Cookie cookie = new Cookie();
                for (int j = 0; j < length; j++)
                {
                    if (j == 0)
                    {
                        str2 = strArray[j];
                        if (str2 != string.Empty)
                        {
                            int index = str2.IndexOf("=");
                            string str4 = str2.Substring(0, index);
                            string str5 = str2.Substring(index + 1, str2.Length - (index + 1));
                            cookie.Name = str4;
                            cookie.Value = str5;
                        }
                    }
                    else
                    {
                        string[] strArray2;
                        if (strArray[j].IndexOf("path", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            str3 = strArray[j];
                            if (str3 != string.Empty)
                            {
                                strArray2 = str3.Split(new char[] { '=' });
                                if (strArray2[1] != string.Empty)
                                {
                                    cookie.Path = strArray2[1];
                                }
                                else
                                {
                                    cookie.Path = "/";
                                }
                            }
                        }
                        else if (strArray[j].IndexOf("domain", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            str3 = strArray[j];
                            if (str3 != string.Empty)
                            {
                                strArray2 = str3.Split(new char[] { '=' });
                                if (strArray2[1] != string.Empty)
                                {
                                    cookie.Domain = strArray2[1];
                                }
                                else
                                {
                                    cookie.Domain = strHost;
                                }
                            }
                        }
                    }
                }
                if (cookie.Path == string.Empty)
                {
                    cookie.Path = "/";
                }
                if (cookie.Domain == string.Empty)
                {
                    cookie.Domain = strHost;
                }
                cookies.Add(cookie);
            }
            return cookies;
        }

        private static ArrayList ConvertCookieHeaderToArrayList(string strCookHeader)
        {
            if (string.IsNullOrEmpty(strCookHeader))
            {
                return new ArrayList();
            }
            strCookHeader = strCookHeader.Replace("\r", "");
            strCookHeader = strCookHeader.Replace("\n", "");
            string[] strArray = strCookHeader.Split(new char[] { ',' });
            ArrayList list = new ArrayList();
            int index = 0;
            int length = strArray.Length;
            while (index < length)
            {
                if (strArray[index].IndexOf("expires=", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    list.Add(strArray[index] + "," + strArray[index + 1]);
                    index++;
                }
                else
                {
                    list.Add(strArray[index]);
                }
                index++;
            }
            return list;
        }

        public static bool DownloadFile(string sourceUrl, string destinationPath)
        {
            new WebClient().DownloadFile(sourceUrl, destinationPath);
            return true;
        }

        public static CookieCollection GetAllCookiesFromHeader(string strHeader, string strHost)
        {
            ArrayList list = new ArrayList();
            CookieCollection cookies = new CookieCollection();
            if (strHeader != string.Empty)
            {
                cookies = ConvertCookieArraysToCookieCollection(ConvertCookieHeaderToArrayList(strHeader), strHost);
            }
            return cookies;
        }

        public static string GetHtml(string url, string accept, string contentType, string referer, string language, CookieContainer cc, System.Text.Encoding encoding, out string returnUrl)
        {
            string str3;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.CookieContainer = cc;
            request.Accept = accept;
            request.ContentType = contentType;
            if (!string.IsNullOrEmpty(referer))
            {
                request.Referer = referer;
            }
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
            if (!string.IsNullOrEmpty(language))
            {
                request.Headers.Add("Accept-Language", language);
            }
            request.Headers.Add("UA-CPU", "x86");
            request.AllowAutoRedirect = true;
            request.KeepAlive = true;
            request.Method = "GET";
            request.UseDefaultCredentials = true;
            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                Stream responseStream = response.GetResponseStream();
                if (request.CookieContainer.IsNotNull())
                {
                    response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                    cc.GetCookieHeader(request.RequestUri);
                }
                string str = response.ResponseUri.ToString();
                returnUrl = str;
                using (StreamReader reader = new StreamReader(responseStream, encoding))
                {
                    str3 = reader.ReadToEnd();
                }
            }
            return str3;
        }

        public static string GetHtml(string url, string accept, string contentType, string referer, string language, string cookies, System.Text.Encoding encoding, out string returnUrl)
        {
            string str3;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.Accept = accept;
            request.ContentType = contentType;
            request.Referer = referer;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
            if (!string.IsNullOrEmpty(language))
            {
                request.Headers.Add("Accept-Language", language);
            }
            request.Headers.Add("UA-CPU", "x86");
            request.AllowAutoRedirect = true;
            request.Method = "GET";
            if (!string.IsNullOrEmpty(cookies))
            {
                request.Headers.Add("Cookie", cookies);
            }
            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                Stream responseStream = response.GetResponseStream();
                if (request.CookieContainer.IsNotNull())
                {
                    response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                }
                string str = response.ResponseUri.ToString();
                returnUrl = str;
                using (StreamReader reader = new StreamReader(responseStream, encoding))
                {
                    str3 = reader.ReadToEnd();
                }
            }
            return str3;
        }

        public static string GetJavaScriptTime()
        {
            long num = 0L;
            DateTime time = new DateTime(0x7b2, 1, 1);
            TimeSpan span = (TimeSpan) (DateTime.Now - time);
            num = (long) (span.TotalMilliseconds + 0.5);
            num += 0xf4240L;
            return num.ToString();
        }

        public static string GetQ(Uri u, string key)
        {
            string query = u.Query;
            int index = query.IndexOf(key + "=");
            int num2 = key.Length + 1;
            int num3 = query.IndexOf("&", (int) (index + num2));
            if (num3 == -1)
            {
                return query.Substring(index + num2, (query.Length - index) - num2);
            }
            return query.Substring(index + num2, (num3 - index) - num2);
        }

        public static string Post(string url, string accept, string contentType, string referer, string language, string postContent, CookieContainer cc, System.Text.Encoding encoding, out string returnUrl)
        {
            string str3;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.CookieContainer = cc;
            request.Accept = accept;
            request.ContentType = contentType;
            request.Referer = referer;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
            if (!string.IsNullOrEmpty(language))
            {
                request.Headers.Add("Accept-Language", language);
            }
            request.Headers.Add("UA-CPU", "x86");
            request.AllowAutoRedirect = true;
            request.UseDefaultCredentials = true;
            request.Method = "POST";
            if (!string.IsNullOrEmpty(postContent))
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), encoding))
                {
                    writer.Write(postContent);
                    writer.Flush();
                }
            }
            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                Stream responseStream = response.GetResponseStream();
                if (request.CookieContainer.IsNotNull())
                {
                    response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                }
                string str = response.ResponseUri.ToString();
                returnUrl = str;
                using (StreamReader reader = new StreamReader(responseStream, encoding))
                {
                    str3 = reader.ReadToEnd();
                }
            }
            return str3;
        }

        public static string Post(string url, string accept, string contentType, string referer, string language, string postContent, ref CookieContainer cc, System.Text.Encoding encoding, out string returnUrl)
        {
            string str3;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.CookieContainer = cc;
            request.Accept = accept;
            request.ContentType = contentType;
            request.Headers["Cache-Control"] = "no-cache";
            request.Referer = referer;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
            if (!string.IsNullOrEmpty(language))
            {
                request.Headers.Add("Accept-Language", language);
            }
            request.Headers.Add("UA-CPU", "x86");
            request.AllowAutoRedirect = true;
            request.UseDefaultCredentials = true;
            request.Method = "POST";
            if (!string.IsNullOrEmpty(postContent))
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), encoding))
                {
                    writer.Write(postContent);
                    writer.Flush();
                }
            }
            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                Stream responseStream = response.GetResponseStream();
                if (request.CookieContainer.IsNotNull())
                {
                    response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                    CookieCollection allCookiesFromHeader = GetAllCookiesFromHeader(response.Headers["Set-Cookie"], response.ResponseUri.Host);
                    cc = new CookieContainer();
                    cc.Add(allCookiesFromHeader);
                }
                string str = response.ResponseUri.ToString();
                returnUrl = str;
                using (StreamReader reader = new StreamReader(responseStream, encoding))
                {
                    str3 = reader.ReadToEnd();
                }
            }
            return str3;
        }

        public static string PostNoAutoRedirect(string url, string accept, string contentType, string referer, string language, string postContent, ref CookieContainer cc, System.Text.Encoding encoding, out string returnUrl)
        {
            string str3;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.CookieContainer = cc;
            request.Accept = accept;
            request.ContentType = contentType;
            request.Referer = referer;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
            if (!string.IsNullOrEmpty(language))
            {
                request.Headers.Add("Accept-Language", language);
            }
            request.Headers.Add("UA-CPU", "x86");
            request.AllowAutoRedirect = false;
            request.UseDefaultCredentials = true;
            request.Method = "POST";
            if (!string.IsNullOrEmpty(postContent))
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), encoding))
                {
                    writer.Write(postContent);
                    writer.Flush();
                }
            }
            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                Stream responseStream = response.GetResponseStream();
                if (request.CookieContainer.IsNotNull())
                {
                    response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                    CookieCollection allCookiesFromHeader = GetAllCookiesFromHeader(response.Headers["Set-Cookie"], response.ResponseUri.Host);
                    cc = new CookieContainer();
                    cc.Add(allCookiesFromHeader);
                }
                string str = response.Headers["Location"];
                returnUrl = str;
                using (StreamReader reader = new StreamReader(responseStream, encoding))
                {
                    str3 = reader.ReadToEnd();
                }
            }
            return str3;
        }

        public static string Resove(string html, string prefix, string subfix)
        {
            int index = html.IndexOf(prefix);
            if (index == -1)
            {
                return null;
            }
            index += prefix.Length;
            int num2 = html.IndexOf(subfix, index);
            return html.Substring(index, num2 - index);
        }

        public static List<string> ResoveList(string html, string prefix, string subfix)
        {
            List<string> list = new List<string>();
            int startIndex = prefix.Length * -1;
            do
            {
                startIndex = html.IndexOf(prefix, (int) (startIndex + prefix.Length));
                if (startIndex == -1)
                {
                    return list;
                }
                startIndex += prefix.Length;
                int index = html.IndexOf(subfix, startIndex);
                string item = html.Substring(startIndex, index - startIndex);
                list.Add(item);
            }
            while (startIndex > -1);
            return list;
        }

        public static string ResoveReverse(string html, string subfix, string prefix)
        {
            int index = html.IndexOf(subfix);
            if (index == -1)
            {
                return null;
            }
            string str = html.Substring(0, index);
            int num2 = str.LastIndexOf(prefix);
            if (num2 == -1)
            {
                return null;
            }
            return str.Substring(num2 + prefix.Length, (str.Length - num2) - prefix.Length);
        }

        public static string SendGet(string url)
        {
            return SendGet(url, null);
        }

        public static string SendGet(string url, string contentType)
        {
            return SendGet(url, contentType, null);
        }

        public static string SendGet(string url, string contentType, ICredentials credentials)
        {
            return SendRequest(url, null, "GET", contentType, null, null, credentials, null, null, Encoding);
        }

        public static string SendGet(string url, string contentType, ICredentials credentials, int? timeout)
        {
            return SendRequest(url, null, "GET", contentType, null, null, credentials, null, timeout, Encoding);
        }

        public static string SendPost(string url, string postData)
        {
            return SendPost(url, postData, null);
        }

        public static string SendPost(string url, string postData, string contentType)
        {
            return SendPost(url, postData, contentType, null);
        }

        public static string SendPost(string url, string postData, string contentType, ICredentials credentials)
        {
            return SendRequest(url, postData, "POST", contentType, null, null, credentials, null, null, Encoding);
        }

        public static string SendPost(string url, string postData, string contentType, ICredentials credentials, int? timeout)
        {
            return SendRequest(url, postData, "POST", contentType, null, null, credentials, null, timeout, Encoding);
        }

        public static string SendRequest(string url, string postData, string requestType, string contentType, string userAgent, bool? keepAlive, ICredentials credentials, IWebProxy proxy, int? timeout, System.Text.Encoding encoding)
        {
            return SendRequest(url, postData, requestType, contentType, userAgent, keepAlive, credentials, proxy, timeout, encoding, null);
        }

        public static string SendRequest(string url, string postData, string requestType, string contentType, string userAgent, bool? keepAlive, ICredentials credentials, IWebProxy proxy, int? timeout, System.Text.Encoding encoding, System.Text.Encoding postDataEncoding)
        {
            if (!string.IsNullOrEmpty(url))
            {
                HttpWebResponse response = null;
                try
                {
                    string str;
                    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
                    request.Method = requestType;
                    if (WebHeaderCollection.IsNotNull())
                    {
                        request.Headers = WebHeaderCollection;
                    }
                    if (credentials.IsNotNull())
                    {
                        request.Credentials = credentials;
                    }
                    if (proxy.IsNotNull())
                    {
                        request.Proxy = proxy;
                    }
                    if (timeout.IsNotNull())
                    {
                        request.Timeout = timeout.Value;
                    }
                    request.ServicePoint.Expect100Continue = false;
                    request.ContentType = !string.IsNullOrEmpty(contentType) ? contentType : "text/xml";
                    if (!string.IsNullOrEmpty(userAgent))
                    {
                        request.UserAgent = userAgent;
                    }
                    if (keepAlive.IsNotNull())
                    {
                        request.KeepAlive = keepAlive.Value;
                    }
                    byte[] buffer = !string.IsNullOrEmpty(postData) ? (postDataEncoding ?? PostDataEncoding).GetBytes(postData) : (postDataEncoding ?? PostDataEncoding).GetBytes(string.Empty);
                    request.ContentLength = buffer.Length;
                    if (requestType.ToUpper() != "GET")
                    {
                        Stream requestStream = request.GetRequestStream();
                        requestStream.Write(buffer, 0, buffer.Length);
                        requestStream.Close();
                    }
                    response = (HttpWebResponse) request.GetResponse();
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream2, encoding ?? Encoding))
                        {
                            str = reader.ReadToEnd();
                        }
                    }
                    return str;
                }
                finally
                {
                    if (response.IsNotNull())
                    {
                        response.Close();
                    }
                }
            }
            throw new Exception("必须指定一个有效的URL。");
        }

        public static System.Text.Encoding Encoding
        {
            get
            {
                return (_encoding ?? (_encoding = System.Text.Encoding.UTF8));
            }
        }

        public static System.Text.Encoding PostDataEncoding
        {
            get
            {
                return (_postDataEncoding ?? (_postDataEncoding = System.Text.Encoding.UTF8));
            }
        }

        public static System.Net.WebHeaderCollection WebHeaderCollection
        {
            get;
            set;
        }
    }
}

